﻿using QLBH.DAO;
using QLBH.DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QLBH.BLO
{
    class BLO_QuanLy
    {
        DAO_QuanLy dao_ql = new DAO_QuanLy();

        public int Insert(QuanLy q, NhanVien nvmg, NhanVien tpmg, NhanVien nvpti, NhanVien tppti, NghiepVu nv, TPA tpa)
        {
            try
            {
                DataTable idmax = Connection_Sql.GetDatatable("select max(CONVERT(INT, MA_QL)) from QuanLy", false);
                int map = 1;
                if (idmax.Rows[0][0].ToString() == "")
                {
                   q.Ma_ql = map.ToString();
                }
                else
                {
                   q.Ma_ql = (int.Parse(idmax.Rows[0][0].ToString()) + 1).ToString();
                }
                string temp=String.Format("select ma_nv from NHANVIEN where TEN_NV='{0}'and MA_PHONG='{1}'and TRUONGPHONG='{2}'",nvmg.Ten_nv,nvmg.Ma_phong,nvmg.Truongphong);
                DataTable manvmg= Connection_Sql.GetDatatable(temp,false);
                nvmg.Ma_nv = manvmg.Rows[0][0].ToString();

                string temp1 = String.Format("select ma_nv from NHANVIEN where TEN_NV='{0}'and MA_PHONG='{1}'and TRUONGPHONG='{2}'", tpmg.Ten_nv, tpmg.Ma_phong, tpmg.Truongphong);
                DataTable matpmg = Connection_Sql.GetDatatable(temp1, false);
                tpmg.Ma_nv = matpmg.Rows[0][0].ToString();

                string temp2 = String.Format("select ma_nv from NHANVIEN where TEN_NV='{0}'and MA_PHONG='{1}'and TRUONGPHONG='{2}'", nvpti.Ten_nv, nvpti.Ma_phong, nvpti.Truongphong);
                DataTable manvpti = Connection_Sql.GetDatatable(temp2, false);
                nvpti.Ma_nv=manvpti.Rows[0][0].ToString();


                string temp3 = String.Format("select ma_nv from NHANVIEN where TEN_NV='{0}'and MA_PHONG='{1}'and TRUONGPHONG='{2}'", tppti.Ten_nv, tppti.Ma_phong, tppti.Truongphong);
                DataTable matppti = Connection_Sql.GetDatatable(temp3, false);
                tppti.Ma_nv=matppti.Rows[0][0].ToString();

                string temp4 = String.Format("select ma_tpa from TPA where TEN_TPA='{0}'", tpa.Ten_TPA);
                DataTable matpa = Connection_Sql.GetDatatable(temp4, false);
                tpa.Ma_TPA = matpa.Rows[0][0].ToString();

                return dao_ql.Insert(q,nvmg,tpmg,nvpti,tppti,nv,tpa);
            }
            catch (System.Exception ex)
            {
                throw new Exception("Lỗi BLO Insert Quan Ly: " + ex.Message);
            }
        }
    }
}
